import { useState } from 'react'
import { View, Text, Image, RichText } from '@tarojs/components'
import audioIcon from '@/img/comm/audio.svg'
import Taro from '@tarojs/taro'

import './index.scss'

const dictionary = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N'
]

interface TopicProps {
  sourceData: API.QuestionProps
  change: (answerId: number) => void
}

const TopicIndex: React.FC<TopicProps> = props => {
  const {
    sourceData: { answerVOList = [], questionJson = [] },
    change
  } = props

  const [audioState, setAudioState] = useState<boolean>(false)

  const handleClickStartAudio = async (url: string) => {
    if (audioState) return

    // 防止重复点击
    await setAudioState(true)
    await playAudio(url)

    // const innerAudioContext = Taro.createInnerAudioContext()
    // innerAudioContext.autoplay = true
    // innerAudioContext.src = url

    // innerAudioContext.onPlay(() => {
    //   setAudioState(true)
    // })
    // innerAudioContext.onEnded(() => {
    //   setAudioState(false)
    //   console.log('audioState222', audioState)
    // })
  }

  const playAudio = (url: string) => {
    const innerAudioContext = Taro.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = url

    innerAudioContext.onPlay(() => {
      setAudioState(true)
    })
    innerAudioContext.onEnded(() => {
      setAudioState(false)
    })
  }

  const getQuestionName = (data: API.TextItem[]) => {
    return (
      <>
        {data?.map((nameItem, index) => {
          if (nameItem.type == 1 && nameItem.name) {
            // if (nameItem.name.indexOf('<p>') != -1) {
            //   const formattedText = nameItem.name.replace(
            //     /(?:\\r\\n|\\r|\\n)/g,
            //     '\n'
            //   )
            //   return (
            //     <View
            //       key={index}
            //       className='title_text'
            //       dangerouslySetInnerHTML={{
            //         __html: formattedText
            //       }}
            //     ></View>
            //   )
            // } else {
            //   return (
            //     <View
            //       key={index}
            //       className='math_question'
            //       dangerouslySetInnerHTML={{ __html: nameItem.name }}
            //     ></View>
            //   )
            // }
            // const formattedText = nameItem.name
            //   .replace(/(?:\\r\\n|\\r|\\n)/g, '\n')
            //   .replace(/&lambda;/g, 'λ')
            //   .replace(/&mu;/g, 'μ')
            //   .replace(/&nbsp;/g, '')
            //   .replace(/&cap;/g, '∩')
            //   .replace(/&Delta;/g, 'Δ')
            //   .replace(/&gt;/g, '>')
            //   .replace(/&infin;/g, '∞')
            //   .replace(/&le;/g, '≤')
            //   .replace(/&plusmn;/g, '±')
            //   .replace(/&alpha;/g, 'α')
            //   .replace(/&beta;/g, 'β')
            const formattedText = nameItem.name
              .replace(/(?:\\r\\n|\\r|\\n)/g, '\n')
              .replace(/font-family: 宋体/g, 'font-family: "PingFang SC"')

            return (
              // <View
              //   key={index}
              //   className='title_text'
              //   dangerouslySetInnerHTML={{
              //     __html: formattedText
              //   }}
              // ></View>
              <View key={index} className='title_text'>
                <RichText nodes={formattedText} />
              </View>
            )
          } else if (nameItem.type == 2) {
            return (
              <Image
                key={index}
                className='audio_png'
                src={audioIcon}
                onClick={() =>
                  audioState ? '' : handleClickStartAudio(nameItem.name)
                }
              />
            )
          } else if (nameItem.type == 3) {
            // return (
            //   <Image
            //     key={index}
            //     className='title_img'
            //     src={nameItem.name}
            //     onClick={() => {
            //       Taro.previewImage({
            //         urls: [nameItem.name]
            //       })
            //     }}
            //   />
            // )
            // const formattedText = nameItem.name
            //   .replace(/&lambda;/g, 'λ')
            //   .replace(/&mu;/g, 'μ')
            //   .replace(/&nbsp;/g, '')
            //   .replace(/&cap;/g, '∩')
            //   .replace(/&Delta;/g, 'Δ')
            //   .replace(/&gt;/g, '>')
            //   .replace(/&infin;/g, '∞')
            //   .replace(/&le;/g, '≤')
            //   .replace(/&plusmn;/g, '±')
            //   .replace(/&alpha;/g, 'α')
            //   .replace(/&beta;/g, 'β')
            //   .replace(/<img/g, '<img mode="widthFix"')
            const formattedText = nameItem.name
              .replace(/(?:\\r\\n|\\r|\\n)/g, '\n')
              .replace(/font-family: 宋体/g, 'font-family: "PingFang SC"')
              .replace(/<img/g, '<img style="position: relative; top: 10px;"')
            return (
              // <View
              //   key={index}
              //   className='math_question flex_row'
              //   dangerouslySetInnerHTML={{ __html: formattedText }}
              // ></View>
              <View key={index} className='math_question'>
                <RichText
                  className='math_question_rich'
                  nodes={formattedText}
                />
              </View>
            )
          }
        })}
      </>
    )
  }

  const handleTopicType = () => {
    return questionJson.findIndex(item => item.type === 2) === 1
      ? '(听力题)'
      : '(单选题)'
  }

  return (
    <>
      <View className='topic_index'>
        <View className='topic_title'>
          <Text className='topic_type'>{handleTopicType()} </Text>
          {getQuestionName(questionJson)}
        </View>
        <View className='options_list flex_column'>
          {answerVOList.map((item, index) => (
            <View className='options_item flex_row' key={item.answerId}>
              <View
                className={item.select ? 'number_box active' : 'number_box'}
                onClick={() => change?.(item.answerId)}
              >
                {dictionary[index]}
              </View>
              <View className='options_text'>
                {item.answerJSON.map((answerItem, idx) => {
                  if (answerItem.type == 1) {
                    // const formattedText = answerItem.name
                    //   .replace(/&lambda;/g, 'λ')
                    //   .replace(/&mu;/g, 'μ')
                    //   .replace(/&nbsp;/g, '')
                    //   .replace(/&cap;/g, '∩')
                    //   .replace(/&Delta;/g, 'Δ')
                    //   .replace(/&gt;/g, '>')
                    //   .replace(/&infin;/g, '∞')
                    //   .replace(/&le;/g, '≤')
                    //   .replace(/&plusmn;/g, '±')
                    //   .replace(/&alpha;/g, 'α')
                    //   .replace(/&beta;/g, 'β')
                    const formattedText = answerItem.name
                      .replace(/(?:\\r\\n|\\r|\\n)/g, '\n')
                      .replace(
                        /font-family: 宋体/g,
                        'font-family: "PingFang SC"'
                      )
                    return (
                      // <View
                      //   key={idx}
                      //   className='math_answer'
                      //   dangerouslySetInnerHTML={{ __html: formattedText }}
                      // ></View>
                      <View key={idx} className='math_answer'>
                        <RichText
                          className='math_answer_rich'
                          nodes={formattedText}
                        />
                      </View>
                    )
                  } else if (answerItem.type == 3) {
                    // const formattedText = answerItem.name
                    //   .replace(/&lambda;/g, 'λ')
                    //   .replace(/&mu;/g, 'μ')
                    //   .replace(/&nbsp;/g, '')
                    //   .replace(/&cap;/g, '∩')
                    //   .replace(/&Delta;/g, 'Δ')
                    //   .replace(/&gt;/g, '>')
                    //   .replace(/&infin;/g, '∞')
                    //   .replace(/&le;/g, '≤')
                    //   .replace(/&plusmn;/g, '±')
                    //   .replace(/&alpha;/g, 'α')
                    //   .replace(/&beta;/g, 'β')
                    //   .replace(/<img/g, '<img mode="widthFix"')
                    const formattedText = answerItem.name
                      .replace(/(?:\\r\\n|\\r|\\n)/g, '\n')
                      .replace(
                        /font-family: 宋体/g,
                        'font-family: "PingFang SC"'
                      )
                    return (
                      // <Image
                      //   key={index}
                      //   className='answer_img'
                      //   src={answerItem.name}
                      //   onClick={() => {
                      //     Taro.previewImage({
                      //       urls: [answerItem.name]
                      //     })
                      //   }}
                      // />

                      // <View
                      //   key={index}
                      //   className='math_answer'
                      //   dangerouslySetInnerHTML={{ __html: formattedText }}
                      // ></View>
                      <View key={index} className='math_answer'>
                        <RichText
                          className='math_answer_rich'
                          nodes={formattedText}
                        />
                      </View>
                    )
                  }
                })}
              </View>
            </View>
          ))}
        </View>
      </View>
    </>
  )
}

export default TopicIndex
